#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/fcntl.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include <pthread.h>
#include<net/if.h>
#include <netdb.h>
#include<sys/ioctl.h>
#include <fcntl.h>
#include<signal.h>
int connfd;
void recvOOB(int sig)
{
    char oob;
    recv(connfd,&oob,1,MSG_OOB);
    fprintf(stderr,"紧急数据：%c",oob);
}
int main(int argc, char const *argv[])
{
    
    int fd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    struct sockaddr_in addr;
    socklen_t len=sizeof(addr);
    bzero(&addr,sizeof(addr));
    addr.sin_family=AF_INET;
    addr.sin_addr.s_addr=htonl(INADDR_ANY);
    addr.sin_port=htons(atoi(argv[1]));
    if(bind(fd,(struct sockaddr *)&addr,len)==-1)
    {
        perror("绑定失败！");
        exit(0);
    }

    listen(fd,3);

    struct sockaddr_in peeraddr;
    len=sizeof(peeraddr);
    bzero(&peeraddr,len);
    connfd =accept(fd,(struct sockaddr *)&peeraddr, &len);
    if(connfd==-1)
    {
        perror("链接失败！");
        exit(0);
    }
    if(connfd > 0)
    {
        printf("有新的客户端连接：[%s:%hu]\n",
                inet_ntoa(peeraddr.sin_addr),
                ntohs(peeraddr.sin_port));
    }
    signal(SIGURG,recvOOB);
    fcntl(connfd,__F_SETOWN,getpid());
    char buf[100];
    while(1)
    {
        bzero(buf,100);
        int n=recv(connfd,buf,100,0);
        if(n<=0)
        {
            break;
        }
        fprintf(stderr,"收到消息：%s",buf);
        send(connfd,buf,strlen(buf),0);
    }

    close(connfd);
    close(fd);
    return 0;
}
